import axios from "axios";

import { userStore } from "@/store/user";
import router from "@/router";
import { ElMessage } from "element-plus";

export const BASE_URL = "https://qianniu.bingdou.site";
axios.defaults.baseURL = BASE_URL;
axios.defaults.headers.post["Content-Type"] = "application/json";

const service = axios.create({
  timeout: 10000,
});

service.interceptors.request.use(
  (config) => {
    const user = userStore();
    if (user.$state.userInfo?.token) {
      // 将 token 添加到请求参数中
      config.data.token = user.$state.userInfo.token;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    const error_res = error.response.data;
    if (error_res.code === 500) {
      localStorage.clear();
      ElMessage.error(error_res.message);
      router.push("/");
    } else {
      ElMessage.error(error_res.message);
    }
    return Promise.reject();
  }
);

export default service;
